import { useEffect, useState, useRef } from 'react'
import { useParams, Link, useNavigate } from 'react-router-dom'
import { useTranslation } from 'react-i18next'
import { createPortal } from 'react-dom'
import {
  ArrowLeft,
  Settings,
  Power,
  PowerOff,
  Package,
  User,
  Calendar,
  Globe,
  Tag,
  Zap,
  AlertCircle,
  CheckCircle,
  ExternalLink
} from 'lucide-react'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '../components/ui/Card'
import { Button } from '../components/ui/Button'
import { Badge } from '../components/ui/Badge'
import { Alert, AlertDescription } from '../components/ui/Alert'
import { PluginErrorBoundary } from '../components/PluginErrorBoundary'

interface MarketItem {
  name: string
  manifest: string
  enabled: boolean
}

interface PluginManifest {
  name: string
  version: string
  description?: string
  author?: string
  homepage?: string
  icon?: string
  tags?: string[]
  engines?: {
    host?: string
  }
  permissions?: string[]
  frontend?: {
    entry?: string
    mountPoints?: string[]
  }
  backend?: {
    entry?: string
    worker?: string
  }
}

interface PluginDetailProps {
  market: MarketItem[]
  pluginUIs: Record<string, () => JSX.Element>
  onTogglePlugin: (plugin: MarketItem) => void
  onConfigurePlugin: (plugin: MarketItem) => void
  theme: 'light' | 'dark'
}

function ShadowRootHost(props: { children: React.ReactNode; style?: React.CSSProperties; className?: string }) {
  const hostRef = useRef<HTMLDivElement | null>(null)
  const [shadow, setShadow] = useState<ShadowRoot | null>(null)
  
  useEffect(() => {
    const el = hostRef.current
    if (!el) return
    let root = el.shadowRoot as ShadowRoot | null
    if (!root) {
      root = el.attachShadow({ mode: 'open' })
      const style = document.createElement('style')
      style.textContent = `:host{display:block} *{box-sizing:border-box}`
      root.appendChild(style)
    }
    setShadow(root)
  }, [])
  
  return (
    <div ref={hostRef} style={props.style} className={props.className}>
      {shadow ? createPortal(props.children, shadow as any) : null}
    </div>
  )
}

export function PluginDetail({
  market,
  pluginUIs,
  onTogglePlugin,
  onConfigurePlugin,
  theme
}: PluginDetailProps) {
  const { t } = useTranslation()
  const { pluginId } = useParams<{ pluginId: string }>()
  const navigate = useNavigate()
  const [manifest, setManifest] = useState<PluginManifest | null>(null)
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)
  const [imageError, setImageError] = useState(false)

  // Find the plugin
  const plugin = market.find(p => {
    const id = p.name.split('/').pop()
    return id === pluginId
  })

  useEffect(() => {
    if (!plugin) {
      setError('Plugin not found')
      setLoading(false)
      return
    }

    const loadManifest = async () => {
      try {
        setLoading(true)
        const res = await fetch(plugin.manifest)
        if (!res.ok) throw new Error(`HTTP ${res.status}`)
        const manifestData = await res.json()
        setManifest(manifestData)
      } catch (err: any) {
        setError(`Failed to load plugin manifest: ${err.message}`)
      } finally {
        setLoading(false)
      }
    }

    loadManifest()
  }, [plugin])

  if (loading) {
    return (
      <div className="container mx-auto px-4 sm:px-6 lg:px-8 py-8">
        <div className="flex items-center justify-center h-64">
          <div className="text-center">
            <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary mx-auto mb-4"></div>
            <p className="text-muted-foreground">{t('pluginDetail.loadingDetails')}</p>
          </div>
        </div>
      </div>
    )
  }

  if (error || !plugin) {
    return (
      <div className="container mx-auto px-4 sm:px-6 lg:px-8 py-8">
        <Alert variant="destructive">
          <AlertCircle className="h-4 w-4" />
          <AlertDescription>{error || 'Plugin not found'}</AlertDescription>
        </Alert>
        <div className="mt-4">
          <Link to="/plugins">
            <Button variant="outline">
              <ArrowLeft className="h-4 w-4 mr-2" />
              Back to Plugins
            </Button>
          </Link>
        </div>
      </div>
    )
  }

  const displayName = manifest?.name || pluginId || 'Unknown Plugin'
  const pluginColor = `bg-${['blue', 'green', 'purple', 'pink', 'indigo', 'yellow', 'red', 'teal'][
    (plugin.name.charCodeAt(0) % 8)
  ]}-500`

  const PluginComponent = pluginUIs[plugin.name]

  return (
    <div className="container mx-auto px-4 sm:px-6 lg:px-8 py-8 space-y-8">
      {/* Header */}
      <div className="flex items-center space-x-4">
        <Button variant="ghost" onClick={() => navigate(-1)}>
          <ArrowLeft className="h-4 w-4 mr-2" />
          Back
        </Button>
        <div className="h-6 w-px bg-border" />
        <nav className="flex items-center space-x-2 text-sm text-muted-foreground">
          <Link to="/plugins" className="hover:text-foreground">Plugins</Link>
          <span>/</span>
          <span className="text-foreground">{displayName}</span>
        </nav>
      </div>

      {/* Plugin Header */}
      <Card>
        <CardHeader>
          <div className="flex items-start space-x-6">
            {/* Plugin Icon */}
            <div className="flex-shrink-0">
              {manifest?.icon && !imageError ? (
                <img 
                  src={manifest.icon} 
                  alt={displayName}
                  className="w-20 h-20 rounded-xl object-cover border-2 border-border"
                  onError={() => setImageError(true)}
                />
              ) : (
                <div className={`w-20 h-20 rounded-xl ${pluginColor} flex items-center justify-center text-white shadow-lg`}>
                  <Package className="w-10 h-10" />
                </div>
              )}
            </div>

            {/* Plugin Info */}
            <div className="flex-1 min-w-0">
              <div className="flex items-center space-x-3 mb-2">
                <h1 className="text-3xl font-bold">{displayName}</h1>
                <Badge variant={plugin.enabled ? 'default' : 'secondary'} className="flex items-center space-x-1">
                  {plugin.enabled ? (
                    <>
                      <Zap className="w-3 h-3" />
                      <span>Active</span>
                    </>
                  ) : (
                    <span>Inactive</span>
                  )}
                </Badge>
              </div>

              <div className="flex items-center space-x-6 text-sm text-muted-foreground mb-4">
                {manifest?.author && (
                  <div className="flex items-center space-x-1">
                    <User className="w-4 h-4" />
                    <span>{manifest.author}</span>
                  </div>
                )}
                {manifest?.version && (
                  <div className="flex items-center space-x-1">
                    <Calendar className="w-4 h-4" />
                    <span>v{manifest.version}</span>
                  </div>
                )}
                {manifest?.homepage && (
                  <a 
                    href={manifest.homepage} 
                    target="_blank" 
                    rel="noopener noreferrer"
                    className="flex items-center space-x-1 hover:text-foreground"
                  >
                    <Globe className="w-4 h-4" />
                    <span>Homepage</span>
                    <ExternalLink className="w-3 h-3" />
                  </a>
                )}
              </div>

              {manifest?.description && (
                <p className="text-muted-foreground mb-4">{manifest.description}</p>
              )}

              {/* Tags */}
              {manifest?.tags && manifest.tags.length > 0 && (
                <div className="flex flex-wrap gap-2 mb-4">
                  {manifest.tags.map((tag) => (
                    <Badge key={tag} variant="outline" className="flex items-center space-x-1">
                      <Tag className="w-3 h-3" />
                      <span>{tag}</span>
                    </Badge>
                  ))}
                </div>
              )}

              {/* Actions */}
              <div className="flex items-center space-x-3">
                <Button
                  variant={plugin.enabled ? 'destructive' : 'default'}
                  onClick={() => onTogglePlugin(plugin)}
                  className="flex items-center space-x-2"
                >
                  {plugin.enabled ? (
                    <>
                      <PowerOff className="w-4 h-4" />
                      <span>Disable</span>
                    </>
                  ) : (
                    <>
                      <Power className="w-4 h-4" />
                      <span>Enable</span>
                    </>
                  )}
                </Button>

                <Button
                  variant="outline"
                  onClick={() => onConfigurePlugin(plugin)}
                  className="flex items-center space-x-2"
                >
                  <Settings className="w-4 w-4" />
                  <span>Configure</span>
                </Button>
              </div>
            </div>
          </div>
        </CardHeader>
      </Card>

      {/* Plugin Interface */}
      {PluginComponent && (
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center space-x-2">
              <div className="w-2 h-2 bg-green-500 rounded-full" />
              <span>Live Plugin Interface</span>
            </CardTitle>
            <CardDescription>
              The plugin's user interface rendered below
            </CardDescription>
          </CardHeader>
          <CardContent>
            <PluginErrorBoundary
              pluginName={displayName}
              onReload={() => window.location.reload()}
            >
              <ShadowRootHost
                className="min-h-[300px] rounded-lg border bg-muted/20 p-6"
                style={{
                  ['--plugin-bg' as any]: theme === 'dark' ? 'hsl(var(--card))' : 'hsl(var(--card))',
                  ['--plugin-fg' as any]: theme === 'dark' ? 'hsl(var(--card-foreground))' : 'hsl(var(--card-foreground))',
                }}
              >
                <PluginComponent />
              </ShadowRootHost>
            </PluginErrorBoundary>
          </CardContent>
        </Card>
      )}

      {/* Technical Details */}
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        {/* Permissions */}
        {manifest?.permissions && manifest.permissions.length > 0 && (
          <Card>
            <CardHeader>
              <CardTitle>Permissions</CardTitle>
              <CardDescription>
                Capabilities this plugin requires
              </CardDescription>
            </CardHeader>
            <CardContent>
              <div className="space-y-2">
                {manifest.permissions.map((permission) => (
                  <div key={permission} className="flex items-center space-x-2">
                    <CheckCircle className="w-4 h-4 text-green-500" />
                    <code className="text-sm bg-muted px-2 py-1 rounded">{permission}</code>
                  </div>
                ))}
              </div>
            </CardContent>
          </Card>
        )}

        {/* Technical Info */}
        <Card>
          <CardHeader>
            <CardTitle>Technical Details</CardTitle>
            <CardDescription>
              Plugin architecture and requirements
            </CardDescription>
          </CardHeader>
          <CardContent className="space-y-4">
            {manifest?.engines?.host && (
              <div>
                <label className="text-sm font-medium">Host Engine</label>
                <p className="text-sm text-muted-foreground">{manifest.engines.host}</p>
              </div>
            )}

            {manifest?.frontend && (
              <div>
                <label className="text-sm font-medium">Frontend</label>
                <div className="text-sm text-muted-foreground space-y-1">
                  {manifest.frontend.entry && <p>Entry: {manifest.frontend.entry}</p>}
                  {manifest.frontend.mountPoints && (
                    <p>Mount Points: {manifest.frontend.mountPoints.join(', ')}</p>
                  )}
                </div>
              </div>
            )}

            {manifest?.backend && (
              <div>
                <label className="text-sm font-medium">Backend</label>
                <div className="text-sm text-muted-foreground space-y-1">
                  {manifest.backend.entry && <p>Entry: {manifest.backend.entry}</p>}
                  {manifest.backend.worker && <p>Worker: {manifest.backend.worker}</p>}
                </div>
              </div>
            )}
          </CardContent>
        </Card>
      </div>
    </div>
  )
}
